package com.whq.common.http;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.nio.charset.Charset;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpClient工具类.
 * 
 * @author wanghuaiqiang
 */
public class HttpUploadUtil {
	private static final Logger LOGGER = LoggerFactory.getLogger(HttpUploadUtil.class);
	private static final Logger LOGGER_THRIFT_REQUEST_RESPONSE = LoggerFactory.getLogger("logger_http_request_response");

	public static String uploadFile(String url, Map<String, String> paramMap, String fileParamName, File file) {
		if (url == null) {
			return "";
		}
		url = url.trim();

		CloseableHttpClient httpClient = HttpClients.createDefault();

		try {
			HttpPost httpPost = new HttpPost(url);

			// 把文件转换成流对象FileBody
			FileBody bin = new FileBody(file);

			MultipartEntityBuilder build = MultipartEntityBuilder.create();
			build.addPart(fileParamName, bin); // 相当于<input type="file" name="media"/>

			for (Iterator<String> iterator = paramMap.keySet().iterator(); iterator.hasNext();) {
				String paramName = (String) iterator.next();
				String paramValue = paramMap.get(paramName);
				if (paramValue == null) {
					paramValue = "";
				}
				StringBody paramBody = new StringBody(paramValue, ContentType.create("text/plain", Consts.UTF_8));

				// 相当于<input type="text" name="name" value="value">
				build.addPart(paramName, paramBody);
			}

			HttpEntity reqEntity = build.build();

			httpPost.setEntity(reqEntity);

			// System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
			// 发起请求 并返回请求的响应
			CloseableHttpResponse response = httpClient.execute(httpPost);
			try {
				// System.out.println("----------------------------------------");
				// 打印响应状态
				// System.out.println(response.getStatusLine());
				// 获取响应对象
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					// 打印响应长度
					// System.out.println("Response content length: " +
					// resEntity.getContentLength());

					String responseBody = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));

					// 打印响应内容
					// System.out.println(responseBody);

					LOGGER_THRIFT_REQUEST_RESPONSE.info("upload file to url[" + url + "] by post, params[" + paramMap + "], response[" + responseBody + "]");
					return responseBody;
				}
				// 销毁
				EntityUtils.consume(resEntity);
			} catch (Exception e) {
				LOGGER.error("parse upload response exception: ", e);
			} finally {
				try {
					response.close();
				} catch (IOException e) {
					LOGGER.error("close response exception: ", e);
				}
			}

		} catch (Exception e) {
			LOGGER.error("upload file exception: ", e);
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				LOGGER.error("close httpclient exception: ", e);
			}
		}

		LOGGER_THRIFT_REQUEST_RESPONSE.info("upload file to url[" + url + "] by post, params[" + paramMap + "], response[]");
		return null;
	}

}
